<?php
namespace app\index\controller;
use app\index\controller\BaseController;
use think\Db;

class MemberController  extends BaseController {

	protected function _initialize() {
		parent::_initialize();
	}

	/**
	 * 会员中心
	 */
	public function index() {
		//获取用户信息
		$user_info = db('member')->where('user_id',session('user_id'))->find();
		//获取用户订单信息
		$order_list = db('good_order')->where('user_id',$user_info['user_id'])->select();
		$count1 = 0;
		$count2 = 0;
		$count3 = 0;
		$count6 = 0;
		foreach($order_list as $kye=>$value){
			
			//待付款
			if($value['status']==1){
				$count1++;		
			}
			
			//待发货
			if($value['status']==2){
				$count2++;
				
			}
			//待确认
			if($value['status']==3){
				$count3++;
				
			}
			//已完成
			if($value['status']==6){
				$count6++;
				
			}
//			$province_ids = $order_list.$value['id'].",";
		}
		/* 
		
		//"昨天:",date("Y-m-d",strtotime("-1 day")), "<hr>";
		*/
		$this->assign('dfkorder', $count1);
		$this->assign('dfhorder', $count2);
		$this->assign('dqrorder', $count3);
		$this->assign('ywcorder', $count6);
		$this->assign('user_info', $user_info);
		return $this->fetch();
	}
	
	public function address() {
		$address_list =db('member_address')
						->where('user_id',session('user_id'))
						->select();
		$this->assign('address_list', $address_list);
		return $this->fetch();
	}
	
	
	public function address_add() {
		if(request()->isPost()) {
			$data = input('post.');
			$result = true;
			Db::startTrans();
			//检查用户是否有地址
			$data['is_default'] = 1;
			$data['province'] = $data['province'];
			$data['city'] = $data['city'];
			$data['district'] = $data['district'];
			$data['consignee'] = $data['consignee'];
			$data['mobile'] = $data['mobile'];
			$data['address'] = $data['address'];
			$data['user_id'] = session('user_id');
			$data['add_time'] = now_time();
			$rest2 = db('member_address')->insert($data);
			if(!$rest2) $result = false;
			
			$address = db('member_address')->where('user_id',session('user_id'))->where('is_default',1)->find(); 
			if($result){
				Db::commit();
				return  json(["code"=>200,"msg"=>"添加成功","data"=>$address]);
			}else{
				Db::rollback();
				return  json(["code"=>403,"msg"=>"添加失败"]);
			}
		}
		
		return $this->fetch();
	}
	
	function address_default(){
		if(request()->isPost()) {
			$address_id = input('address_id');
			
			if (!is_numeric($address_id)) {
				return  json(["code"=>405,"msg"=>"数据异常"]);
			}
			
			$rest1 = db('member_address')
						->where('user_id', session('user_id'))
						->update(['is_default' => 0]);
			if($rest1){
				$rest2 = db('member_address')
						->where('id', $address_id)
						->where('user_id', session('user_id'))
						->update(['is_default' => 1]);
				if($rest2){
					return  json(["code"=>200,"msg"=>"修改成功"]);
				}else{
					return  json(["code"=>403,"msg"=>"修改失败"]);
				}
			}else{
				return  json(["code"=>405,"msg"=>"修改失败"]);
			}
		}
	}
	
	
	
	
	function address_update() {
		$address_id = input('address_id');
		if (!is_numeric($address_id)) {
			return  json(["code"=>405,"msg"=>"数据异常"]);
		}
		$address_info = db('member_address')->where('id', $address_id)->where('user_id', session('user_id'))->find();

		$this->assign('address_info',$address_info);
		
		if(request()->isPost()) {
			$data = input('post.');
			unset($data['address_id']);
			$result = db('member_address')
						->where('id', $address_id)
						->where('user_id', session('user_id'))
						->update($data);
			
			if($result) {
				return  json(["code"=>200,"msg"=>"修改成功",'url'=>url('member/address')]);
			} else {
				return  json(["code"=>403,"msg"=>"修改失败"]);
			}
		}
		
		
		
		return $this->fetch();
	}
	function address_del() {
		if(request()->isPost()) {
			$address_id = input('address_id');
			
			if (!is_numeric($address_id)) {
				return  json(["code"=>405,"msg"=>"数据异常"]);
			}
			
			$result = db('member_address')->where('id', $address_id)->where('user_id', session('user_id'))->delete();
			
			if($result) {
				return  json(["code"=>200,"msg"=>"删除成功"]);
			} else {
				return  json(["code"=>403,"msg"=>"删除失败"]);
			}
		}
	}
	public function edit_password() {
		if(request()->isPost()){
			$xpassword['password']=md5_salt(input('xpassword'));
			$jpassword['password']=md5_salt(input('jpassword'));
			$user_info = db('member')->where('user_id',session('user_id'))->where($jpassword)->find();
			if($user_info){
				$rest = db('member')->where('user_id', session('user_id'))->update($xpassword);
				if($rest){
					return json(['code'=>200,'msg'=>'修改成功','url'=>'/index/index/login']);
				}else{
					return json(['code'=>405,'msg'=>'修改失败']);
				}
			}else{
				return json(['code'=>403,'msg'=>'旧密码不对']);
			}
		}
		return $this->fetch();
	}
	public function orders() {
		
		$where['user_id'] = session('user_id');
		if(input('status')>0){
			$where['status'] = input('status');
		}else{
			$where['status'] = ['<>',8];
		}
		
		//获取用户订单信息
		$order_list = db('good_order')
						->where($where)
						->order('add_time desc')
						->select();
						
		foreach($order_list as $key=>&$value){
			//获取订单详情
			$order_item = db('order_items')->where('order_id',$value['id'])->select();
			$value['order_item'] = $order_item;
		}
		$this->assign('status',input('status'));
		$this->assign('order_list',$order_list);
		return $this->fetch();
	}
	
	
	function order_page(){
		
		//获取用户订单信息
		$order_info = db('good_order')
						->where('id',input('order_id'))
						->find();
		if($order_info){
			$order_item = db('order_items')->where('order_id',$order_info['id'])->select();
			
			$order_info['order_item'] = $order_item;
			
		}else{
			return $this->fetch('none_style');
		}
		
		$this->assign('order_info',$order_info);
		return $this->fetch();
	}
	
	public function buy() {
		//获取用户地址信息
		$user_address = db('member_address')
						->where('user_id',session('user_id'))
						->where('is_default',1)
						->find();
		if(!$user_address){
			$this->redirect('member/address');
		}
		$order_ids = input('order_id');
		
		$order_arr = explode(",",$order_ids);
		
		$order_list = array();
		$total_money = 0;
		foreach($order_arr as $key=>$value){
			//获取订单信息
			$order_info = db('good_order')->where('id',$value)->find();
			$total_money = bcadd($order_info['total_price'], $total_money, 2);
			//获取订单详情
			$oreder_item  = db('order_items')->where('order_id',$order_info['id'])->select();
			$order_info['order_item'] = $oreder_item;
			$order_list[] = $order_info;
			
		}
		
		$this->assign('order_arr',$order_ids);		
		$this->assign('user_address',$user_address);
		$this->assign('order_list',$order_list);
		$this->assign('total_money',$total_money);		
		return $this->fetch();
	}
	
	function order_buy1(){
		if (request()->isPost()) {
			$goods_info = db('goods')->where('goods_id',input('goods_id'))->find();
			if($goods_info){
				$goods_info['goods_num'] = input('goods_num');
				
				$result = true;
				Db::startTrans();
				$order_sn = order_create_no();
				//生成订单
				$rest1 = add_order($goods_info,$order_sn,1);
				
				if(!$rest1) $result =false;
				
				$order_id = db('good_order')->getLastInsID();
				
				//生成订单详情
				$rest2 = add_order_item($goods_info,$order_id,1);
				if(!$rest2) $result =false;
				
				
				//更新订单信息
				$rest3 = update_order($order_id,input('express_type'),input('address_id'),input('memo'));
				if(!$rest3) $result =false;
				
				//计算订单金额
				$total_price = bcmul($goods_info['cost_price'],$goods_info['goods_num'], 2);
				//获取用户信息
				$user_info = db('member')->where('user_id',session('user_id'))->find();
				//检查用户余额
				if(bccomp($user_info['score'], $total_price, 2)<0){
					return json(['code'=>403,'msg'=>'账户余额不足']);
				}
				
				//减去用户余额
				$rest4 = db('member')->where('user_id', session('user_id'))->setDec('score',$total_price);
				if(!$rest4) $result = false;
				//用户消费余额变化日志
				$rest5 = add_member_consume($user_info['user_id'],$total_price,$order_sn,3,'商城消费'.$total_price);
				if(!$rest5) $result = false;
				
				//新增支付日志
				$rest6 = add_pay_log(session('user_id'),$goods_info['agent_id'],$total_price,2,$order_sn,
				5,1,"购买商品",$order_id,now_time());
				if(!$rest6) $result = false;
				
				//支付回调
				$rest7 = pay_callback($order_sn);
				if(!$rest7) $result = false;
				
				
				if($result){
					Db::commit();
					return json(['code'=>200,'msg'=>'购买成功','url'=>url('member/index')] );
				}else{
					Db::rollback();
					return json(['code'=>403,'msg'=>'购买失败']);
				}
			}else{
				return json(['code'=>403,'msg'=>'商品不存在，数据异常']);
			}
		}
		//获取用户地址信息
		$user_address = db('member_address')
						->where('user_id',session('user_id'))
						->where('is_default',1)
						->find();
		if(!$user_address){
			$this->redirect('member/address');
		}
		//获取商品信息
		$goods_info = db('goods')->where('goods_id',input('goods_id'))->find(); 
		//获取商家信息
		$agent_name = db('agent')->where('id',$goods_info['agent_id'])->value('agent_name');	
		$goods_info['agent_name'] = $agent_name;
		//获取用户信息
		$user_info = db('member')->where('user_id',session('user_id'))->find();
		$this->assign('goods_info',$goods_info);
		$this->assign('user_address',$user_address);
		return $this->fetch();
	}
	
	/**
	 * Post方法
	 * $body     商品描述
	 * $attach   附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用。
	 * $order_no 订单号
	 * $total_fee 价格
	 */
		public function wechat() {
			header('Access-Control-Allow-Origin:*');
			import("payment.wxpay.lib.WxPayApi");
			import("payment.wxpay.JsApiPay");
			
			$order_type =  input('order_type');
			$order_sn = input('order_sn');
			
			if($order_type==1){	//充值会费
				$result = add_pay_log(session('user_id'),0,input('money'),$order_type,$order_sn,2,1,input("WIDsubject"),0,now_time());
			}elseif($order_type==2){//订单
				//$result = add_pay_log(session('user_id'),$agent_id,$balance,$order_type,$order_sn,$pay_type,$state,$message,$order_id,$pay_time)
			} elseif($order_type==3){//充值小卡
				$result = add_pay_log(session('user_id'),0,input('money'),$order_type,$order_sn,2,1,input("WIDsubject"),0,now_time());
			}
			if(!$result){
				echo "支付失败！";
				exit;
			}
			
			//①、获取用户openid
			$tools = new \JsApiPay();
			//$openId = $tools->GetOpenid();
			//②、统一下单
			$input = new \WxPayUnifiedOrder();
			// 商品描述
			$input->SetBody(input("WIDsubject"));
			// 商品补充说明
			$input->SetAttach(input("WIDbody"));
			// 商户订单号32位以下
			$input->SetOut_trade_no($order_sn);
			// 价格，单位分
			//$input->SetTotal_fee(input("WIDtotal_fee")*100);
			$input->SetTotal_fee(1);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			// 回调通知处理
			$input->SetNotify_url(config('main_url').'index/member/wechat_notify');
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid(input("openid"));
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			echo "jsonpCallback"."(".$jsApiParameters.")";
			exit;
	}

	//微信支付回调
	public function wechat_notify() {
		import("payment.wxpay.wechat_callback");
		//获取支付回调结果。
		$notify = new \wechat_callback();
		
		$notify->Handle(false);
		
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$data = $notify->FromXml($xml);
		
		//处理回调
		if($data['return_code'] == "SUCCESS"){
			//查找当前支付日志状态
			$cut_paylog_info = db('paylog')->where('order_sn',$data['out_trade_no'])->find();
			//判断当前是否支付完成
			if($cut_paylog_info['state'] != 2){
				pay_callback($data['out_trade_no']);
			}else{
				$rest = $notify->ToXml();
				echo $rest;
			}
		}
	}
	
	function test_pay(){
		pay_callback(input("sn"));
	}
	
	/**
	 * 支付宝手机支付
	 * $params
	 */
	public function alipay($params = '') {
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipaySubmit");
		
		$order_type =  input('order_type');
		$order_sn = input('order_sn');
		
		if($order_type==1){	//充值会费
				$result = add_pay_log(session('user_id'),0,input('money'),$order_type,$order_sn,3,1,input("WIDsubject"),0,now_time());
				$WIDshow_url = 'http://'.$_SERVER['HTTP_HOST']."index/pay_success";
		
		}elseif($order_type==2){//订单
			//$result = add_pay_log(session('user_id'),$agent_id,$balance,$order_type,$order_sn,$pay_type,$state,$message,$order_id,$pay_time)
			//$WIDshow_url = "";
		}elseif($order_type==3){//充值小卡
				$result = add_pay_log(session('user_id'),0,input('money'),$order_type,$order_sn,2,1,input("WIDsubject"),0,now_time());
				$WIDshow_url = 'http://'.$_SERVER['HTTP_HOST']."index/pay_success";
		}
		if(!$result){
			echo "支付失败！";
			exit;
		}
		// 获取配置信息
		$alipey_info =  config('alipay');
		//合作身份者ID，签约账号，以2088开头由16位纯数字组成的字符串，查看地址：https://b.alipay.com/order/pidAndKey.htm
		$alipay_config['partner'] = $alipey_info['alipay_partner'];
		//收款支付宝账号，以2088开头由16位纯数字组成的字符串，一般情况下收款账号就是签约账号
		$alipay_config['seller_id'] = $alipey_info['alipay_seller_id'];
		// MD5密钥，安全检验码，由数字和字母组成的32位字符串，查看地址：https://b.alipay.com/order/pidAndKey.htm
		$alipay_config['key'] = $alipey_info['alipay_key'];
		// 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
		$alipay_config['notify_url'] = url("member/alipay_notify", '', '', true);
		$alipay_config['return_url'] = url("index/pay_success", '', '', true);
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['input_charset'] = strtolower('utf-8');
		//ca证书路径地址，用于curl中ssl校验, 请保证cacert.pem文件在当前文件夹目录中
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		$alipay_config['payment_type'] = "1";
		$alipay_config['service'] = "alipay.wap.create.direct.pay.by.user";
		
		/**************************请求参数**************************/
		//商户订单号，商户网站订单系统中唯一订单号，必填
		$out_trade_no = $order_sn;
		//订单名称，必填
		$subject = $_POST['WIDsubject'];
		//付款金额，必填
		//$total_fee = $_POST['WIDtotal_fee'];
		$total_fee = 0.01;
		//收银台页面上，商品展示的超链接，必填
		$show_url = $WIDshow_url;
		//商品描述，可空
		$body = $_POST['WIDbody'];
		/************************************************************/
		//构造要请求的参数数组，无需改动
		$parameter = array(
			"service" => $alipay_config['service'],
			"partner" => $alipay_config['partner'],
			"seller_id" => $alipay_config['seller_id'],
			"payment_type" => $alipay_config['payment_type'],
			"notify_url" => $alipay_config['notify_url'],
			"return_url" => $alipay_config['return_url'],
			"_input_charset" => trim(strtolower($alipay_config['input_charset'])),
			"out_trade_no" => $out_trade_no,
			"subject" => $subject,
			"total_fee" => $total_fee,
			"show_url" => $show_url,
			//"app_pay" 		 => "Y", //启用此参数能唤起钱包APP支付宝
			"body" => $body,
		);
		//建立请求
		$alipaySubmit = new \AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
		echo $html_text;
	}
	
	//支付宝回调model1
	public function alipay_notify() {
		// 获取配置信息
		$alipey_info =  config('alipay');
		
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipayNotify");
		// 获取缓存配置
		$alipay_config['partner'] 	= $alipey_info['alipay_partner'];
		$alipay_config['key'] 		= $alipey_info['alipay_key'];
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['cacert'] 	= getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		//计算得出通知验证结果
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if ($verify_result) {
			//验证成功
			//请在这里加上商户的业务逻辑程序代
			//获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
			//商户订单号
			$out_trade_no = $_POST['out_trade_no'];
			//支付宝交易号
			$trade_no = $_POST['trade_no'];
			//交易状态
			$trade_status = $_POST['trade_status'];

			if ($_POST['trade_status'] == 'TRADE_FINISHED') {
				//判断该笔订单是否在商户网站中已经做过处理
			} else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
			}
			pay_callback($out_trade_no);
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
			echo "success";
			return $this->toJson(200, '支付成功', $member);
			//请不要修改或删除
		} else {
			//验证失败
			echo "fail";
		}
	}
	
/**
 * 获取用户openid
 * $redirect='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
 */
	function get_user_openid($redirect_url){
		$wxpay_info = config('wxpay');
		$app_id = $wxpay_info['APPID'];
		$auth_code=input("code");
		$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$app_id.'&redirect_uri='.urlencode($redirect_url).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
		if(!$auth_code){
			Header("Location: $url");
			exit;
		}else{
			if(!session("cut_openid")){
				$open_id = user_wx_id($auth_code);
				session("cut_openid",$open_id);
			}else{
				$open_id = session("cut_openid");
			}
		}
		
		return $open_id;
	}
	//订单
	public function member_order(){
		$type = input("type");
		if($type!=0){
			$map['status'] = $type;
			$where['a.status'] = $type;
		}

		$map['user_id'] = session('user_id');
		$where['a.user_id'] = session('user_id');
		
		$result2 = db('order_items')->field('order_id,thumb')->select();
		
		$ordercount = db('order_items')->field('order_id,count(id) as count')->group('order_id')->buildSql();
		
		$result = db('good_order a')
				->field('a.id,a.order_sn,a.status,a.pay_price,a.add_time,c.count')
				->join($ordercount.' c','a.id=c.order_id')
				->where($where)->order('add_time desc')->select();

		$this->assign('res2',$result2);
		$this->assign('res',$result);
		$this->assign('type',$type);
		return $this->fetch();		
	}
	//个人资料
	public function update(){
			if ($this->request->isPost()) {
			$data = $this->request->post();
			$data['update_time'] = now_time();
			unset($data['file']);
			$result = db('member')->where('user_id', session('user_id'))->update($data);
			if ($result) {
				$this->success('保存成功');
			} else {
				$this->error('保存失败');
			}
		}
		$result = db('member')->where('user_id', session('user_id'))->select();
		$this->assign('res',$result);
		return $this->fetch();
		
	}
	//修改密码
	public function member_pwd(){
		if(request()->isPost()){
			$xpassword['password']=md5_salt(input('xpassword'));
			$jpassword['password']=md5_salt(input('jpassword'));
			$user_info = db('member')->where('user_id',session('user_id'))->where($jpassword)->find();
			if($user_info){
				$rest = db('member')->where('user_id', session('user_id'))->update($xpassword);
				if($rest){
					return json(['code'=>200,'msg'=>'修改成功','url'=>'/index/index/login']);
				}else{
					return json(['code'=>405,'msg'=>'修改失败']);
				}
			}else{
				return json(['code'=>403,'msg'=>'旧密码不对']);
			}
		}
		return $this->fetch();
		
	}
	
	//获取地址
	function  getaddress(){
		$address = '';
		if(session('user_id')){
			$address = db('member_address')->where('user_id',session('user_id'))->where('is_default',1)->find(); 
		}
		if($address){
			return  json(["code"=>200,"data"=>$address]);
		}else{
			return  json(["code"=>403,"msg"=>"请添加地址"]);
		}
		
	}
	
	//获取自提地址
	function  getztaddress(){
		$address = db('address')->where('shop_id',input('agent_id'))->select(); 
		return  json(["code"=>200,"data"=>$address]);
	}
	
	//提交订单
	public function tjorder(){
		if ($this->request->isPost()) {
			$postdata = $this->request->post();
			
			$addcount = db('member_address')->where('user_id',session('user_id'))->select();
			if(!$addcount){
				return json(["code"=>403,'msg'=>'请先设置地址!']);	
			}			
			
//			$pay_type = input('post.pay_type');
//			if (!$pay_type) {
//				$this->error('请选择支付方式');
//			}

			$result = true;
			Db::startTrans();
			
			//新增订单
			$userid = 	session('user_id');
			//获取用户信息
			$user_info = db('member')->where('user_id',$userid)->find();
			
			$address = db('member_address')->where('user_id',$userid)->where('is_default', 1)->find();

			$result = true;
			//新增订单
			$order['user_id'] = $userid;
			$order['total_price'] = $postdata['price'];
			$order['agent_id'] = $postdata['agent_id'];
			$agentinfo = db('agent')->where('id',$postdata['agent_id'])->find();
			$order['agent_name'] = $agentinfo['agent_name'];
			$orderNo = build_order_no();
			$order['order_sn'] = $orderNo;
			$order['add_time'] = now_time();
			$order['status'] = 1;  // 1待付款 2待发货 3待收货 4待评价 5已完成 6已关闭7退货
			$order['address'] = $address['address'] ;
			$order['pay_type'] = $postdata['pay_type'];
			$order['ztaddress'] = $postdata['ztaddress'];;
			$order['pay_price'] = $postdata['price'];
			$order['memo'] = $postdata['memo'];
			$order['mobile'] = $user_info['mobile'] ;

			// 增加待付款订单
			$orderId = db('good_order')->insertGetId($order);
			if (!$orderId) {
				$result = false;
			}
			
			if($orderId){
				$goods = isset($postdata['goods'])?$postdata['goods']:null;//商品
				if($goods){
					foreach($goods as $i){
						$items[] = array("add_time"=>now_time(),"thumb"=>$i['logo'],"order_id"=>$orderId,"goods_id"=>$i['id'],"price"=>$i['sale_price'],"total_price"=>$i['sale_price']*$i['num'],"nums"=>$i['num'],"goods_name"=>$i['name']);
						$sql="update cz_goods set stock =stock - ".$i['num'].",sales=sales+".$i['num']." where goods_id = ".$i['id'];
						DB::execute($sql);
					}
					$orderItems = db('order_items')->insertAll($items);
					if (!$orderItems) {
						$result = false;
					}					
				}					
			}
			
			if($result){
				// 提交事务
				Db::commit();
				
				//短信提醒
//				return json(['code'=>200,'msg'=>'支付成功','order_id'=>$orderId]);
				dump('事务提交ok');
			}else{
				//回滚
	    		Db::rollback();
				return json(['code'=>401,'msg'=>'订单处理失败']);
			}
			
			
//			return json(["code"=>200,'msg'=>'支付成功','order_id'=>$orderId]);
			    
		    // 商品的销量累积
//			db('goods')->where('id',$value['id'])->setInc('sale',$value['goods_num']);
			$this->redirect(url('pay/dopayshop', array('sn' => $orderNo)));
			
		}		
	}
	
	function cancel_order($id){
		if($this->request->isPost()){
			$order_info = db('good_order')->where('id',$id)->find();
			if($order_info){
				 $result = db('good_order')->where('id',$order_info['id'])->update(['status'=>8]);
				 if($result){
				 	return json(['code'=>200,'msg'=>'订单已取消']);
				 }else{
				 	return json(['code'=>403,'msg'=>'订单取消失败']);
				 }
			}else{
				return json(['code'=>403,'msg'=>'订单不存在，数据异常']);
			}
		}
	}
	
		
	/**
	 * 收货
	 */
	function qrorder($id) {
		if($this->request->isPost()) {
			if (!is_numeric($id)) {
				$this->error('参数错误');
			}			
			$order_info = db('good_order')->where('id',$id)->find();
			if (!$order_info) {
				return json(['code'=>403,'msg'=>'产品不存在或已收货']);
			}
			
			$result = $this->orderFengy($order_info);
			
			if ($result) {
				return json(['code'=>200,'msg'=>'收货成功']);
			} else {
				return json(['code'=>403,'msg'=>'收货失败']);
			}			

		}
	}
	
	//订单奖金处理
	protected function orderFengy($order) {
		//待确认订单
		if($order['status']==3){
			// 判断订单状态, 如果订单未做过处理, 则处理自己核心业务
			$result = true;
			
			Db::startTrans();
			
			//获取订单金额
			$pay_price = $order['pay_price'];
			
			//添加商家资金变化日志
			$adata['agent_id'] = $order['agent_id'];
			$adata['balance'] = $pay_price; //变化金额
			$adata['order_sn'] = $order['order_sn']; // 订单号
			$adata['order_type'] = 1;//订单
			$adata['message'] = '用户下单';//奖金
			$adata['add_time'] = now_time();
			
			$aresult = db('agent_charge')->insert($adata);												

			if(!$aresult){
				$result = false;
			}				
			
			//订单剩余金额计入商家余额
			$abalanceresult = db('agent')->where('id',$order['agent_id'])->setInc('balance', $adata['balance']);			
			if(!$abalanceresult){
				$result = false;
			}
			
			//订单剩余金额计入商家累计收入
			$atoalresult = db('agent')->where('id',$order['agent_id'])->setInc('total_income', $adata['balance']);			
			if(!$atoalresult){
				$result = false;
			}
						
			
			//修改订单状态
			$data['status'] = 6;
			$data['confirm_time'] = now_time();
			$result = db('good_order')->where('id', $order['id'])->update($data);
			if(!$result){
				$result = false;
			}
			
			if($result){
				// 提交事务
			    Db::commit();    
				
			}else{
				// 回滚事务
			    Db::rollback();
			    $this->error('收货失败');
			}
			return $result;	
		}
	}

	public function ordertj(){
		if ($this->request->isPost()) {
			$postdata = $this->request->post();
			
			$agent_id = $postdata['agent_id'];
			$price = $postdata['price'];
			$goods = isset($postdata['goods'])?$postdata['goods']:null;//商品
			cookie('goodscar',$goods);
			$data['agent_id'] = $agent_id;
			$data['sfprice'] = $price;
			return json(['code'=>200,'msg'=>'操作成功','data'=>$data]);
		}	
	
		return $this->fetch();	
	}
	
	public function orderzf(){
		$this->assign('agent_id', input('agent_id'));
		$this->assign('price', input('sfprice'));
		$this->assign('user_id', session('user_id'));
		//获取省份信息
		$province_list = db('sys_district')->where('pid',0)->select(); 
		
		$province_ids = "";
		foreach($province_list as $kye=>$value){
			$province_ids = $province_ids.$value['id'].",";
		}
		
		//获取市信息
		$city_list = db('sys_district')
						->where('pid','in', substr($province_ids ,0,strlen($province_ids)-1))
						->select(); 
						
		$district_ids = "";
		foreach($city_list as $kye=>$value){
			$district_ids = $district_ids.$value['id'].",";
		}			
						
		//获取区县信息
		$district_list = db('sys_district')
						->where('pid','in', substr($district_ids ,0,strlen($district_ids)-1))
						->select(); 		
	
		$this->assign('province_list', $province_list);
		$this->assign('city_list', $city_list);
		$this->assign('district_list', $district_list);
		return $this->fetch();
	}
	
	
	//调用微信支付 
	public function order_buy(){
		if ($this->request->isPost()) {
			$result = true;
			Db::startTrans();
			//新增订单
			$userid = session('user_id');
			//获取用户信息
			$user_info = db('member')->where('user_id',$userid)->find();
			
			$address = db('member_address')->where('user_id',$userid)->where('is_default', 1)->find();
			if(!$address){
				$result = false;
			}

			$result = true;
			//新增订单
			$order['user_id'] = $userid;
			$order['total_price'] = input('ddprice');
			$order['agent_id'] = input('agent_id');
			$agentinfo = db('agent')->where('id',1)->find();
			$order['agent_name'] = $agentinfo['agent_name'];
			$orderNo = build_order_no();
			$order['order_sn'] = $orderNo;
			$order['add_time'] = now_time();
			$order['status'] = 1;  // 1待付款 2待发货 3待收货 4待评价 5已完成 6已关闭7退货
			$order['address'] = $address['address'] ;
			$order['pay_type'] = 1;//input('pay_type');
			$order['ztaddress'] = input('ztads');
			$order['pay_price'] = input('ddprice');
			$order['memo'] = input('memo');
			$order['mobile'] = $user_info['mobile'] ;

			// 增加待付款订单
			$orderId = db('good_order')->insertGetId($order);
			if (!$orderId) {
				$result = false;
			}
			
			if($orderId){
				$goods = cookie('goodscar');//商品
				if(!$goods){
					$this->error('账单为空');
				}
				if($goods){
					foreach($goods as $i){
						$items[] = array("add_time"=>now_time(),"thumb"=>$i['logo'],"order_id"=>$orderId,"goods_id"=>$i['id'],"price"=>$i['sale_price'],"total_price"=>$i['sale_price']*$i['num'],"nums"=>$i['num'],"goods_name"=>$i['name']);
						$sql="update cz_goods set stock =stock - ".$i['num'].",sales=sales+".$i['num']." where goods_id = ".$i['id'];
						DB::execute($sql);
					}
					$orderItems = db('order_items')->insertAll($items);
					if (!$orderItems) {
						$result = false;
					}					
				}					
			}
			
			if($result){
				// 提交事务
				Db::commit();
				
				//短信提醒
				dump('事务提交ok');
			}else{
				//回滚
	    		Db::rollback();
				$this->error('订单处理失败');
			}

			$this->redirect(url('pay/dopayshop', array('sn' => $orderNo)));	
		}
	}
}
